package com.tkc.common.util.log.interceptor;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.tkc.common.util.log.LoggerUtil;
import com.tkc.common.util.log.Loggers;

/**
 * 
 * @Function: Esl层调用监控
 * 
 * @Project :assessmenttask 
 * @Package :com.tkc.common.util.log.interceptor 
 * @File :EslInterceptor.java 
 * @ClassName: EslInterceptor  
 * 
 * @author tankaichao 
 * @email cgztkc@126.com 
 * @Date 2016年8月9日下午7:03:19
 * @since JDK 1.8 
 *
 */
public class EslInterceptor implements MethodInterceptor {

    /** 摘要日志 */
    private static final Logger DIGEST_LOGGER = Loggers.ESL_DIGEST_LOGGER;
    /** 出入参日志 */
    private static final Logger BIZ_LOGGER = Loggers.ESL_LOGGER;

    /**
     * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
     */
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        //开始时间。
        long start = System.currentTimeMillis();

        //DOMaper和method
        Method method = invocation.getMethod();
        Object[] params = invocation.getArguments();
        String className = method.getDeclaringClass().getSimpleName();
        String packageName = method.getDeclaringClass().getPackage().getName();
        String appName = StringUtils.substringAfterLast(packageName, ".");
        String methodName = method.getName();

        //是否成功
        boolean hasError = false;
        try {
            LoggerUtil.info(BIZ_LOGGER, "Invoking methmod:{}.{}.{} with params:{}", packageName,
                className, methodName, params);
            Object result = invocation.proceed();
            LoggerUtil.info(BIZ_LOGGER, "Result of methmod:{}.{}.{} with params:{},result:{}",
                packageName, className, methodName, params.toString(), result);
            return result;
        } catch (Exception e) {
            hasError = true;
            throw e;
        } finally {
            long diffTime = System.currentTimeMillis() - start;
            String result = hasError ? "F" : "T";
            StringBuilder sb = new StringBuilder("(");
            sb.append(appName).append(",");
            sb.append(className).append(",").append(methodName).append(",").append(result)
                .append(",").append(diffTime).append("ms)");
            if (DIGEST_LOGGER.isInfoEnabled()) {
                DIGEST_LOGGER.info(sb.toString());
            }
        }
    }
}